<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>可编辑的 div</title>
		<style>
			.view,
			.edit {
				height: 150px;
				width: 400px;
				font-family: sans-serif;
				font-size: 14px;
				display: block;
			}

			.view {
				/* padding + border = 3px */
				padding: 2px;
				border: 1px solid black;
			}

			.edit {
				/* replace padding with border (still 3px not to shift the contents) */
				border: 3px solid blue;
				padding: 0px;
			}

			.edit:focus {
				/* remove focus border in Safari */
				outline: none;
			}
		</style>
	</head>
	<body>
		<ul>
			<li>点击下面的这个 div 来进行编辑。</li>
			<li>按 Enter 键或者通过 blur 来保存结果。</li>
		</ul>

		允许输入 HTML。

		<div id="view" class="view">Text</div>

		<script>
			let area = null
			const view = document.getElementById('view')

			view.onclick = function () {
				editStart()
			}

			function editStart() {
				area = document.createElement('textarea')
				area.className = 'edit'
				area.value = view.innerHTML

				// 如果在文本域中按下 Enter 键，将调用失去焦点的事件。
				area.onkeydown = function (event) {
					if (event.key === 'Enter') {
						this.blur()
					}
				}

				area.onblur = function () {
					editEnd()
				}

				view.replaceWith(area) // 将div元素替换为文本域元素
				area.focus()
			}

			function editEnd() {
				view.innerHTML = area.value
				area.replaceWith(view)
			}
		</script>
	</body>
</html>
